/*
-----------------------------------------------------------------------------
This source file is part of as4game
	(ActionScript For Game Engine)
For the latest info, see http://as4game.googlecode.com

Copyright (c) 2000-2011 Hproof Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
package org.ext.loader.ogre
{
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.utils.ByteArray;
	import flash.utils.setTimeout;
	
	import org.as4game.common.loader.RawLoader;
	import org.as4game.resource.anim.Animation;
	import org.as4game.resource.bitmap.Material;
	import org.as4game.resource.manager.ResourceManager;
	import org.as4game.resource.mesh.Mesh;
	import org.as4game.resource.mesh.SubMesh;
	import org.as4game.resource.skeleton.Bone;
	import org.as4game.resource.skeleton.Skeleton;

	/**
	 * 读入 OGRE 模型资源
	 */
	public class OgreLoader extends EventDispatcher
	{
		private var _path:String;
		private var _name:String;
		private var _matInfo:Object;
		private var _mesh:Mesh;
		private var _skeleton:Skeleton;
		
		//
		public function OgreLoader(){
		}
		
		/**
		 * 读入多个资源
		 * @param pathnames 资源路径信息, =[ [path0, name0], [path1, name1], ...]
		 */
		static public function loadAll( pathnames:Array, next:Function, charSet:String=null ):void{
			
			StreamSerialiser.charSet = (charSet || "utf-8");
			
			var cur:int = 0;
			var loader:OgreLoader = new OgreLoader;
			loadOne();
			
			function loadOne():void{
				
				if( cur >= pathnames.length ){
					setTimeout( next, 1 );
					return;
				}
				
				//
				var path:String = pathnames[cur][0];
				var name:String = pathnames[cur][1];
				loader.addEventListener( Event.COMPLETE, onCompleteOne);
				loader.loadAll( path, name );
			}
			function onCompleteOne(e:Event):void{
				cur ++;
				loadOne();
			}
		}
		
		/**
		 * 读入资源
		 * @param path 资源路径
		 * @param name 资源名, 后面会自动增加  .mesh, .material, .skeleton 扩展名
		 */
		public function loadAll( path:String, name:String ):void{
			trace(this, "loadAll", name, path);
			
			// 检测已存在
			var mesh_name:String = name + ".mesh";
			if( ResourceManager.getMesh( mesh_name ) != null ){
				trace("exist");
				loadAllComplete();
				return;
			}
			
			// 开始加载
			var ch:String = path.charAt( path.length-1 );
			if( ch != "/" && ch != "\\" ) path += "/";
			
			_path = path;
			_name = name;
			_matInfo = null;
			_mesh = null;
			_skeleton = null;
			
			// 加载材质
			loadMaterial();
		}
		
		// 全部加载完成
		private function loadAllComplete():void{
			if( _mesh ){
				ResourceManager.setMesh( _name + ".mesh", _mesh );
			}
			if( _skeleton ){
				_mesh.setSkeleton( _skeleton );
				ResourceManager.setSkeleton( _name + ".skeleton", _skeleton );
			}
			
			setTimeout( dispatchEvent, 1, new Event(Event.COMPLETE) );
		}
		
		/**
		 * 读入材质
		 */
		private function loadMaterial():void{
			var name:String = _name + ".material";
			var url:String = _path + name;
			trace("load material", name );
			RawLoader.loadRaw( url, 1, loadMaterialComplete );
		}
		private function loadMaterialComplete( txt:String ):void{
			
			// 解析材质信息
			var matInfo:Object = _matInfo = parse_material( txt );
			
			// 读入每个贴图
			var taskId:int = 0;
			var tasks:Array = [];
			var matname:String, txtname:String;
			
			for(matname in matInfo ){
				tasks.push( [ matname, matInfo[matname] ] ); 
			}
			loadOne();
			
			//
			function loadOne():void{
				if( taskId >= tasks.length ){
					onCompleteAll();
					return;
				}
				
				matname = tasks[ taskId ] [0];
				txtname = tasks[ taskId ] [1];
				if( ResourceManager.getMaterial( txtname ) != null ){
					trace("exist texture", txtname );
					taskId ++;
					loadOne();
				}
				else{
					trace("load texture", txtname );
					RawLoader.loadRaw( _path + txtname, 2, onCompleteOne );
				}
			}
			function onCompleteOne( disp:DisplayObject ):void{
				var bmp:Bitmap = disp as Bitmap;
				if( bmp ){
					var m:Material = Material.fromBitmap( bmp.bitmapData );
					ResourceManager.setMaterial( txtname, m );
				}
				taskId ++;
				loadOne();
			}
			function onCompleteAll():void{
				loadMesh();
			}
		}
		
		/**
		 * 读入网格
		 */
		private function loadMesh():void{
			var name:String = _name + ".mesh";
			var url:String = _path + name;
			trace("load mesh", name );
			RawLoader.loadRaw( url, 0, loadMeshComplete );
		}
		private function loadMeshComplete( ba:ByteArray ):void{
			
			var mesh:Mesh = _mesh = MeshSerializer.importMesh( ba );
			mesh.mTextureAlias = _matInfo;
			
			if( mesh.mSkeletonName ){
				
				var maxBonesPerSubMesh:int = 0;
				for each(var sub:SubMesh in mesh.mSubMeshList ){
					var local2global:Vector.<uint>;
					if( sub.useSharedVertices ) local2global = mesh.mShaderGeomBuffer.bone_local2global;
					else local2global = sub.geomBuffer.bone_local2global;
					if( local2global.length > maxBonesPerSubMesh ){
						maxBonesPerSubMesh = local2global.length;
					}
				}
				trace("max bones per subMesh:", maxBonesPerSubMesh);
			
//				mesh.mSkeletonName = "walk.skeleton";
				loadSkeleton( mesh.mSkeletonName );
			}
			else{
				loadAllComplete();
			}
		}
		
		/**
		 * 读入骨骼
		 */
		private function loadSkeleton( skelName:String ):void{
			var name:String = skelName;
			var skeleton:Skeleton = ResourceManager.getSkeleton( name ); 
			if( skeleton != null ){
				trace("exist skeleton", name );
				_mesh.setSkeleton( skeleton ); 
				loadAllComplete();
			}
			
			var url:String = _path + name;
			trace("load skeleton", name );
			RawLoader.loadRaw( url, 0, loadSkeletonComplete );
		}
		private function loadSkeletonComplete( ba:ByteArray ):void{
			
			var skeleton:Skeleton = _skeleton = SkeletonSerializer.importSkeleton( ba );
			trace("num bones:", skeleton.numBones );

			// bind?
			if( skeleton.mAnimationsList.length == 1 ){
				var ani:Animation = skeleton.mAnimationsList[0];
				if( ani.mNodeTrackList == null ){
//					skeleton.clearAnimation( 
					var name:String = _name + ".animation";
					trace("load bind-animation", name);
					RawLoader.loadRaw( _path + name, 1, onLoadAnimationBind);
					return;
				}
			}
			
			// no bind
			loadAllComplete();
		}
		
		// 读入动画绑定
		private function onLoadAnimationBind( txt:String ):void{
			
			var task:Array = [];
			var cur:int;
			
			var reg:RegExp = /^\s*\<STRING\>\s*FILE\s*:\s*(?P<fname>\S+)\s*$/gm;
			var obj:Object = reg.exec( txt );
			while( obj ){
				task.push( obj.fname );
				obj = reg.exec( txt );
			}
			
			loadOne();
			
			//
			function loadOne():void{
				if( cur >= task.length ){
					onCompleteAll();
					return;
				}
				var fname:String = task[ cur ];
				trace("load animation", fname );
				RawLoader.loadRaw( _path + fname , 0, onCompleteOne );
			}
			
			function onCompleteOne( ba:ByteArray ):void{
				var skeleton:Skeleton = SkeletonSerializer.importSkeleton( ba );
//				skeleton.mergyAnimation( _skeleton );
//				_skeleton = skeleton;
				_skeleton.mergyAnimation( skeleton );
				cur ++;
				loadOne();
			}
			
			function onCompleteAll():void{
				loadAllComplete();
			}
		}
		
		
		/**
		 * 解析材质
		 * @param source 输入源文件
		 * @return 返回材质信息, obj[materialName] = filename
		 */
		static public function parse_material( source:String ):Object{
			var ret:Object = {};
			var matname:String;
			var txtname:String;
			
			var reg_material:RegExp = /^\s*(material\s+(?P<matname>\S+))|(texture\s+(?P<txtname>\S+))\s*$/gm;
			var obj:Object = reg_material.exec( source );
			while( obj )
			{
				if( obj.matname ){
					matname = obj.matname;
				}
				if( obj.txtname && ! ret[ matname ] ){
					txtname = obj.txtname;
					ret[ matname ] = txtname;
				}
				obj = reg_material.exec( source );
			}
			return ret;
		}
	}
}